<template>
  <div class="layout-container">
    <split-pane split="vertical" :min-percent="17" :default-percent="19" :max-percent="50">
      <template slot="paneL">
        <div class="left-container">
          <el-input
            v-model="filterText"
            placeholder="输入用户组名称进行过滤"
          />
          <el-button type="text" icon="el-icon-plus" @click="handleCreate">新增用户组</el-button>
          <el-tree
            ref="tree"
            style="margin-top: 20px"
            class="filter-tree"
            :data="userGroupTreeOptions"
            :props="defaultProps"
            default-expand-all
            highlight-current
            draggable
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :allow-drop="allowDrop"
            node-key="id"
            @node-click="handleNodeClick"
            @node-drop="handleDragEnd"
          >
            <span slot-scope="{ node,data }" class="custom-tree-node">
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <span v-if="editGroup.editId === data.id && editGroup.isEdit">
                <i :class="node.isCurrent ?'co-icon-zg-folder-opened-fill' : 'co-icon-folder_opened'" />
                <el-input
                  v-model="editGroup.editInfo"
                  size="mini"
                  placeholder="请输入内容"
                  @keyup.enter.native="() => updateData(node, data)"
                />
              </span>
              <span v-else>
                <i :class="node.isCurrent ?'co-icon-zg-folder-opened-fill' : 'co-icon-folder_opened'" />
                <span>{{ node.label }}</span>
              </span>
              <span v-if="editGroup.editId === data.id && editGroup.isEdit">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-check"
                  @click.stop.prevent="() => updateData(node, data)"
                />
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-close"
                  @click.stop.prevent="() => handleClose(node, data)"
                />
              </span>
              <span v-else>
                <el-button
                  style="margin-right: 10px"
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click.stop.prevent="() => handleUpdate(node, data)"
                />
                <el-popover
                  :value="delId === data.id"
                  placement="top"
                  width="160"
                >
                  <p>确定删除该用户组吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="delId = ''">取消</el-button>
                    <el-button type="primary" size="mini" @click.stop.prevent="() => handleRemove(node, data)">确定</el-button>
                  </div>
                  <el-button
                    slot="reference"
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                  />
                </el-popover>
              </span>
            </span></el-tree>
        </div>
      </template>
      <template slot="paneR">
        <div class="right-container">
          <basic-page-vxe
            ref="basePage"
            list-api="findUserByUserGroupId"
            del-api="deleteSysUser"
            :search-form="basicData.searchForm"
            :search-handle="basicData.searchHandle"
            :search-other-data="basicData.searchData"
            :columns="basicData.columns"
          />
        </div>
      </template>
    </split-pane>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 100%">
        <el-form-item label="用户组名称" prop="groupName">
          <el-input v-model="temp.groupName" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSysUserGroup, updateSysUserGroup, findSysUserGroupAll, deleteSysUserGroupById } from '@/api/admin'
import splitPane from 'vue-splitpane'
export default {
  name: '',
  components: {
    splitPane
  },
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: '员工编号', field: 'username' }, type: 'copy' },
          { config: { title: '姓名', field: 'nickname' }},
          { config: { title: '手机号', field: 'mobile' }},
          { config: { title: '角色', field: 'roleIdCn' }},
          { config: { title: '所属机构', field: 'orgIdCn' }},
          { config: { title: '状态', field: 'status', width: 70 }, type: 'render',
            render: (h, scope) => {
              if (scope.row.status === 1) {
                return (
                  <el-tag effect='plain' type='success'>正常</el-tag>
                )
              } else {
                return (
                  <el-tag effect='plain' type='danger'>禁用</el-tag>
                )
              }
            } },
          {
            config: {
              title: '操作',
              width: '90'
            }, type: 'render',
            render: (h, scope) => {
              return (
                <div>
                  <el-button plain size='mini' type='warning' v-permission="'delete'" onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 移除</el-button>
                </div>
              )
            }
          }
        ],
        searchData: {
          id: ''
        },
        searchForm: [],
        searchHandle: [
          { label: '新增用户', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreateUser() } }
        ]
      },
      typ: [],
      detail: {},
      userGroupTreeOptions: [],
      orgName: '',
      temp: {
        id: undefined,
        status: 1,
        prefix: '86'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      editGroup: {
        isEdit: false,
        editId: 0,
        editInfo: ''
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        groupName: [{ required: true, validator: this.checkUsername, trigger: ['blur', 'change'] }]
      },
      downloadLoading: false,
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'groupName'
      },
      delId: ''
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getType()
  },
  mounted() {
  },
  methods: {
    handleNodeClick(val) {
      console.log(val)
      this.basicData.searchData.id = val.id
      this.$refs.basePage.getList()
    },
    // 判断目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      if (type === 'inner') {
        return false
      } else {
        return true
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.groupName.indexOf(value) !== -1
    },
    // 业务逻辑
    getType() {
      findSysUserGroupAll().then(response => {
        this.userGroupTreeOptions = response.data
        this.basicData.searchForm[2].options = response.data
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 1,
        prefix: '86'
      }
    },
    handleDragEnd(draggedNode, node, type, ev) {
      console.log('tree drag over: ', draggedNode.key)
      console.log('tree drag : ', node.key)
      console.log('tree drag : ', type)
    },
    handleCreate() {
      this.resetTemp()
      this.orgName = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.getType()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.userGroupTreeOptions.length === 0) {
            this.temp.displayOrder = 1000
          } else {
            this.temp.displayOrder = this.userGroupTreeOptions[this.userGroupTreeOptions.length - 1].displayOrder + 1000
          }
          addSysUserGroup(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleUpdate(node, data) {
      this.editGroup.isEdit = true
      this.editGroup.editId = data.id
      this.editGroup.editInfo = data.groupName
    },
    updateData(node, data) {
      if (!this.editGroup.editInfo) {
        this.$message.error('请输入用户组名称！')
        return false
      } else {
        if (this.editGroup.editInfo.length > 2 && this.editGroup.editInfo.length < 65) {
          const tempData = {}
          tempData.id = this.editGroup.editId
          tempData.groupName = this.editGroup.editInfo
          tempData.displayOrder = data.displayOrder
          updateSysUserGroup(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getType()
            this.handleClose()
          })
        } else {
          this.$message.error('请输入用户组度最小为3最大为64！')
          return false
        }
      }
    },
    handleClose(node, data) {
      this.editGroup = {
        isEdit: false,
        editId: 0,
        editInfo: ''
      }
    },
    handleRemove(node, data) {
      console.log(node)
      console.log(data)
      const loading = this.$loading({
        lock: true,
        text: '删除中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      deleteSysUserGroupById(data.id).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        loading.close()
        this.getType()
      }).catch(() => {
        loading.close()
      })
    },
    handleCreateUser() {

    },
    handleReset() {
      this.getType()
      this.$refs.basePage.getList()
    },
    checkUsername(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入用户组名称！'))
      } else {
        if (value.length > 2 && value.length < 65) {
          callback()
        } else {
          return callback(new Error('用户名长度最小为3最大为64！'))
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
.custom-tree-node{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
